<?php

namespace S\WeChat\Util;

use S\Config;
use S\Crypt\Aes;
use S\Request;

class OAuthCookie
{

    const DATA_OPEN_ID  = 'open_id';
    const DATA_UNION_Id = 'union_id';

    public static function set($official_account, $open_id, $union_id = '', $expires_in = 0)
    {
        $data = [
            static::DATA_OPEN_ID  => $open_id,
            static::DATA_UNION_Id => $union_id,
        ];

        return setcookie(
            static::genName($official_account),
            static::encrypt($official_account, $data),
            ($expires_in ?: static::config($official_account, 'expire')) + time() - static::config('expire_safety'),
            static::config($official_account, 'path'),
            static::config($official_account, 'domain'),
            static::config($official_account, 'secure'),
            static::config($official_account, 'http_only')
        );

    }

    public static function getOpenId($official_account)
    {
        return static::get($official_account, static::DATA_OPEN_ID) ?: '';
    }

    public static function getUnionId($official_account)
    {
        return static::get($official_account, static::DATA_UNION_Id) ?: '';
    }

    public static function get($official_account, $name = '')
    {
        $data = static::decrypt(
            $official_account,
            Request::cookie(static::genName($official_account), '')
        );

        if ($name && is_array($data)) {
            return array_key_exists($name, $data) ? $data[$name] : '';
        }
        return $data;
    }

    public static function del($official_account)
    {
        return setcookie(
            static::genName($official_account),
            '',
            time() - 1,
            static::config($official_account, 'path'),
            static::config($official_account, 'domain'),
            static::config($official_account, 'secure'),
            static::config($official_account, 'http_only')
        );
    }

    protected static function genName($official_account)
    {
        return '_' . substr(md5($official_account), 0, 15);
    }

    protected static function config($official_account, $option = '')
    {
        $option = $option ? ".{$option}" : '';
        return Config::confSecurity("wechat.{$official_account}.oauth.cookie{$option}");

    }

    protected static function decrypt($official_Account, $encrypted)
    {
        return json_decode(Aes::decrypt(base64_decode($encrypted), static::config($official_Account, 'aes_key')), true);
    }

    protected static function encrypt($official_Account, $data)
    {
        return base64_encode(Aes::encrypt(json_encode($data), static::config($official_Account, 'aes_key')));
    }


}
